package com.pingan.myBatis.crypt.handler;

import com.pingan.myBatis.crypt.annotations.CryptField;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @AUTHOR:LIUCHAO; 加密bean类型的数据
 * @DATE: 2020/11/30 16:39
 */
public class BeanHandler {
    /**
     * bean 加密
     *
     * @param val
     * @throws Exception
     */
    public static void beanEncrypt(Object val) throws Exception {
        Class objClazz = val.getClass();
        Field[] objFields = objClazz.getDeclaredFields();
        for (Field field : objFields) {
            CryptField cryptField = field.getAnnotation(CryptField.class);
            if (cryptField != null && cryptField.encrypt()) {
                field.setAccessible(true);
                Object fieldValue = field.get(val);
                if (fieldValue == null) {
                    continue;
                }
                if (field.getType().equals(String.class)) {
                    field.set(val, StringHandler.stringEncrypt((String) fieldValue));
                    continue;
                }
                if (field.getType().equals(List.class)) {
                    field.set(val, ListHandler.listEncrypt((List) fieldValue, Boolean.TRUE));
                    continue;
                }
            }
        }
    }

    /**
     * bean 解密
     *
     * @param val
     * @throws Exception
     */
    public static void beanDecrypt(Object val) throws Exception {
        Class objClazz = val.getClass();
        Field[] objFields = objClazz.getDeclaredFields();
        for (Field field : objFields) {
            CryptField cryptField = field.getAnnotation(CryptField.class);
            if (cryptField != null && cryptField.decrypt()) {
                field.setAccessible(true);
                Object fieldValue = field.get(val);
                if (fieldValue == null) {
                    continue;
                }
                if (field.getType().equals(String.class)) {
                    field.set(val, StringHandler.stringDecrypt((String) fieldValue));
                    continue;
                }
                if (field.getType().equals(List.class)) {
                    field.set(val, ListHandler.listDecrypt((List) fieldValue, Boolean.TRUE));
                    continue;
                }
            }
        }
    }
}
